package cn.knight.org.service.impl;

import cn.knight.basic.service.impl.BaseServiceImpl;
import cn.knight.org.domain.Department;


import cn.knight.org.mapper.DepartmentMapper;
import cn.knight.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;



    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        String dirPath = "";
        //先在mapper.xml中返回自增id,在判断他有没有上级部门
        if (department.getParent().getId() ==null){
            dirPath = "/"+department.getId();
        }else {
            Long id = department.getParent().getId();
            Department parentDept = departmentMapper.loadById(id);
            if(parentDept != null) {
                dirPath = parentDept.getDirPath() + "/" + department.getId();
            }
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);

    }

    @Override
    @Transactional
    public void update(Department department) {
        String dirPath = "";
        //先在mapper.xml中返回自增id,在判断他有没有上级部门
        if (department.getParent() ==null){
            dirPath = "/"+department.getDirPath();
        }else {
            Long id = department.getParent().getId();
            Department parentDept = departmentMapper.loadById(id);
            if(parentDept != null) {
                dirPath = parentDept.getDirPath() + "/" + department.getId();
            }
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }




    @Override
    public List<Department> tree() {
        //获取所有数据
        List<Department> depts = departmentMapper.loadAll();
        //创建一个装最终结果的集合
        List<Department> deptList =  new ArrayList<Department>();
        //为了解决时间复杂度，转为map
        Map<Long, Department> deptMap = new HashMap<>();
        for(Department department : depts){
            deptMap.put(department.getId(),department);
        }
        //先把一级数据找出来
        for (Department dept : depts){
            if (dept.getParentId() == null){
                deptList.add(dept);
            }else {
                Department department = deptMap.get(dept.getParentId());
                if (department != null){
                    department.getChildren().add(dept);
                }
            }
        }

        return deptList;
    }
}
